package cn.tedu.jdbc.Demo;

import cn.tedu.jdbc.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @author Justin Parker
 * @author 2024/8/1 下午10:48
 * @version 1.0
 */
/** 更改操作*/
public class UpdateDemo {
    public static void Update(){
        try(Connection connection = DBUtil.getConnection()){
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名：");
            String oldUsername = scanner.nextLine();
            System.out.println("请输入密码：");
            String oldPassword= scanner.nextLine();

            String sql1 = "select id from userinfo where username =? and password = ?";
            String sql2 = "update userinfo set username = ?,password = ?,nickname =?,age = ? where username = ? and password = ?";

            PreparedStatement ps1 = connection.prepareStatement(sql1);
            PreparedStatement ps2 = connection.prepareStatement(sql2);
            ps1.setString(1,oldUsername);
            ps1.setString(2,oldPassword);
            ResultSet resultSet = ps1.executeQuery();
            if (resultSet.next()){
                System.out.println("请输入新用户名：");
                String newUsername = scanner.nextLine();
                System.out.println("请输入新密码：");
                String newPassword = scanner.nextLine();
                System.out.println("请输入新昵称：");
                String newNickname = scanner.nextLine();
                System.out.println("请输入新年龄：");
                int newAge = scanner.nextInt();

                ps2.setString(1,newUsername);
                ps2.setString(2,newPassword);
                ps2.setString(3,newNickname);
                ps2.setInt(4,newAge);
                ps2.setString(5,oldUsername);
                ps2.setString(6,oldPassword);

                int i = ps2.executeUpdate();
                if (i>0){
                    System.out.println("恭喜你！更改成功");
                }else {
                    System.out.println("更改失败");
                }
            }else {
                System.out.println("用户名或密码错误");
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
